import {createMemoryHistory, createRouter, RouteRecordNameGeneric} from "vue-router";
import {get} from "@/axios"
import { generateRoutes } from "@/utils/dynamicRoutes"


const routes = [
    {
        path:"/",
        name:"home",
        component: ()=> import("@/components/home-view.vue")
    },
    {
        path:"/main",
        name:"main",
        component: () => import('@/components/main/main-view.vue')
    },
    {
      path: "/login",
      name: "login" ,
      component: () => import('@/components/user/login-view.vue')  
    },
    {
	    path: '/:pathMatch(.*)*',
	    component: () =>import('@/components/error-page/404.vue')
	}
]


const router = createRouter({
    history: createMemoryHistory(),
    routes:routes
})
const menuList:any = [];
const token = localStorage.getItem("token")
if(!(token === "" || token === null)){
   menuList.push(await get("/Menu/GetMenuList"))  
}


let routesInitialized = false;

 function initDynamicRoutes() {
  try {
      // console.log(menuList[0].data)
    const menuData = menuList;
    // const dynamicRoutes = generateRoutes(menuData.data);
      //2024 0805  打开之后发现菜单数据必须要接一个[0]
    const dynamicRoutes = generateRoutes(menuData[0].data);
    dynamicRoutes.forEach((route:any) => {
      router.addRoute("main",route);
    });
    routesInitialized = true;
  } catch (error) {
    console.error('Failed to initialize dynamic routes:', error);
  }
}

// 初始化路由
initDynamicRoutes();

router.beforeEach(async (to, from, next) => {
    if (!routesInitialized) {
    await initDynamicRoutes();
  }
  console.log(to, from)
  next();
});


export default router;